<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑访客单' : '新建访客单'"
    width="700px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
    >
      <!-- 核心必填字段 -->
      <el-form-item
        label="客户"
        prop="lead_id"
      >
        <el-select
          v-model="formData.lead_id"
          filterable
          placeholder="输入客户姓名或手机号搜索"
          style="width: 100%"
          :loading="loadingLeads"
          @focus="loadLeads"
        >
          <el-option
            v-for="lead in leads"
            :key="lead.id"
            :label="`${lead.name} - ${lead.phone}`"
            :value="lead.id"
          >
            <span>{{ lead.name }}</span>
            <span style="color: #8492a6; font-size: 12px; margin-left: 8px">
              {{ lead.phone }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="经纪人"
            prop="agent_id"
          >
            <el-select
              v-model="formData.agent_id"
              filterable
              placeholder="选择经纪人"
              style="width: 100%"
              :loading="loadingAgents"
              @focus="loadAgents"
            >
              <el-option
                v-for="agent in agents"
                :key="agent.id"
                :label="agent.full_name || agent.email"
                :value="agent.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="带看日期"
            prop="visit_date"
          >
            <el-date-picker
              v-model="formData.visit_date"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 可选字段 -->
      <el-divider content-position="left">
        <el-text
          type="info"
          size="small"
        >
          以下为可选信息
        </el-text>
      </el-divider>

      <el-form-item
        label="房源"
        prop="property_id"
      >
        <el-select
          v-model="formData.property_id"
          filterable
          clearable
          placeholder="输入小区名或房号搜索（可留空）"
          style="width: 100%"
          :loading="loadingProperties"
          @focus="loadProperties"
        >
          <el-option
            v-for="property in properties"
            :key="property.id"
            :label="`${property.community_name} ${property.room_number}`"
            :value="property.id"
          >
            <span>{{ property.community_name }}</span>
            <span style="color: #8492a6; font-size: 12px; margin-left: 8px">
              {{ property.room_number }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="带看时间"
            prop="visit_time"
          >
            <el-time-picker
              v-model="formData.visit_time"
              placeholder="选择时间"
              value-format="HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="停留时长(分钟)"
            prop="duration_minutes"
          >
            <el-input-number
              v-model="formData.duration_minutes"
              :min="0"
              :max="1440"
              placeholder="停留时长"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item
            label="满意度(1-5星)"
            prop="satisfaction"
          >
            <el-rate
              v-model="formData.satisfaction"
              show-score
              text-color="#ff9900"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="意向度"
            prop="intention"
          >
            <el-select
              v-model="formData.intention"
              placeholder="请选择意向度"
              style="width: 100%"
            >
              <el-option
                label="高"
                value="high"
              />
              <el-option
                label="中"
                value="medium"
              />
              <el-option
                label="低"
                value="low"
              />
              <el-option
                label="无"
                value="none"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item
        label="优点标签"
        prop="pros_tags"
      >
        <el-input
          v-model="formData.pros_tags"
          placeholder="如: 户型好,采光好,交通便利 (逗号分隔)"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        label="缺点标签"
        prop="cons_tags"
      >
        <el-input
          v-model="formData.cons_tags"
          placeholder="如: 楼层低,租金高,噪音大 (逗号分隔)"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        label="备注"
        prop="notes"
      >
        <el-input
          v-model="formData.notes"
          type="textarea"
          :rows="4"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'VisitorSheetDialog' })
/**
 * 访客单对话框组件 - 优化版
 * 使用可搜索下拉选择器替代ID输入
 */
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useVisitorSheetStore } from '@/stores/visitor-sheet'
import { useUserStore } from '@/stores/user'
import type { FormInstance, FormRules } from 'element-plus'
import type { VisitorSheet, VisitorSheetCreate, VisitorSheetUpdate, Lead, Property, User } from '@/api/types'
import { leadApi } from '@/api'
import { propertyApi } from '@/api'
import notify from '@/utils/notify'

// ========== Props & Emits ==========
interface Props {
  modelValue: boolean
  visitorSheetData?: VisitorSheet | null
}

const props = defineProps<Props>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// ========== Store ==========
const visitorSheetStore = useVisitorSheetStore()
const userStore = useUserStore()

// ========== 响应式数据 ==========
const visible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val),
})

const isEdit = computed(() => !!props.visitorSheetData)

const formRef = ref<FormInstance>()
const loading = ref(false)

// 下拉列表数据
const leads = ref<Lead[]>([])
const properties = ref<Property[]>([])
const agents = ref<User[]>([])

// 加载状态
const loadingLeads = ref(false)
const loadingProperties = ref(false)
const loadingAgents = ref(false)

const formData = reactive<VisitorSheetCreate & { id?: number }>({
  lead_id: 0,
  property_id: 0,
  agent_id: 0,
  visit_date: '',
  visit_time: undefined,
  duration_minutes: undefined,
  satisfaction: undefined,
  pros_tags: '',
  cons_tags: '',
  intention: 'medium',
  notes: '',
})

// 表单验证规则
const rules: FormRules = {
  lead_id: [
    { required: true, message: '请选择客户', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择客户', trigger: 'change' },
  ],
  agent_id: [
    { required: true, message: '请选择经纪人', trigger: 'change' },
    { type: 'number', min: 1, message: '请选择经纪人', trigger: 'change' },
  ],
  visit_date: [{ required: true, message: '请选择带看日期', trigger: 'change' }],
  // 房源改为可选
  property_id: [],
  satisfaction: [
    {
      type: 'number',
      min: 1,
      max: 5,
      message: '满意度必须在1-5星之间',
      trigger: 'change',
    },
  ],
  duration_minutes: [
    {
      type: 'number',
      min: 0,
      max: 1440,
      message: '时长必须在0-1440分钟之间',
      trigger: 'blur',
    },
  ],
}

// ========== 方法 ==========

/**
 * 加载客户列表
 */
const loadLeads = async () => {
  if (leads.value.length > 0) return // 已加载过
  loadingLeads.value = true
  try {
    const res = await leadApi.getList({ page: 1, page_size: 200 })
    leads.value = res.items
  } catch (error) {
    console.error('加载客户列表失败', error)
    notify.error('加载客户列表失败')
  } finally {
    loadingLeads.value = false
  }
}

/**
 * 加载房源列表
 */
const loadProperties = async () => {
  if (properties.value.length > 0) return // 已加载过
  loadingProperties.value = true
  try {
    const res = await propertyApi.getList({ page: 1, page_size: 100 })
    properties.value = res.items
  } catch (error) {
    console.error('加载房源列表失败', error)
    notify.error('加载房源列表失败')
  } finally {
    loadingProperties.value = false
  }
}

/**
 * 加载经纪人列表（临时方案：从客户列表的 owner 中提取）
 * TODO: 后端需要提供 /api/v1/users 接口
 */
const loadAgents = async () => {
  if (agents.value.length > 0) return // 已加载过
  loadingAgents.value = true
  try {
    // 临时方案：从当前用户获取
    if (userStore.userInfo) {
      agents.value = [userStore.userInfo]
      // 默认选中当前用户
      if (!formData.agent_id) {
        formData.agent_id = userStore.userInfo.id
      }
    }
  } catch (error) {
    console.error('加载经纪人列表失败', error)
    notify.error('加载经纪人列表失败')
  } finally {
    loadingAgents.value = false
  }
}

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (props.visitorSheetData) {
    Object.assign(formData, props.visitorSheetData)
  } else {
    Object.assign(formData, {
      lead_id: 0,
      property_id: 0, // 0 表示未选择房源
      agent_id: userStore.userInfo?.id || 0, // 默认当前用户
      visit_date: '',
      visit_time: undefined,
      duration_minutes: undefined,
      satisfaction: undefined,
      pros_tags: '',
      cons_tags: '',
      intention: 'medium',
      notes: '',
    })
  }
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    loading.value = true
    try {
      let success = false
      if (isEdit.value && formData.id) {
        // 编辑
        const { id, ...updateData } = formData
        const result = await visitorSheetStore.updateVisitorSheet(
          id,
          updateData as VisitorSheetUpdate
        )
        success = !!result
      } else {
        // 新建：按接口显式构造
        const createData: VisitorSheetCreate = {
          lead_id: formData.lead_id,
          property_id: formData.property_id || 0, // 如果未选择，传0
          agent_id: formData.agent_id,
          visit_date: formData.visit_date,
          visit_time: formData.visit_time,
          duration_minutes: formData.duration_minutes,
          satisfaction: formData.satisfaction,
          pros_tags: formData.pros_tags,
          cons_tags: formData.cons_tags,
          intention: formData.intention,
          notes: formData.notes,
        }
        const result = await visitorSheetStore.createVisitorSheet(createData)
        success = !!result
      }

      if (success) {
        emit('success')
      }
    } finally {
      loading.value = false
    }
  })
}

/**
 * 关闭对话框
 */
const handleClose = () => {
  formRef.value?.resetFields()
  visible.value = false
}

// ========== 监听 ==========
watch(
  () => props.visitorSheetData,
  () => {
    initFormData()
  },
  { immediate: true }
)

// 组件挂载时预加载数据
onMounted(() => {
  loadLeads()
  loadProperties()
  loadAgents()
})
</script>
